package com.ganwenlong.collections;

import java.lang.reflect.Constructor;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

class SetType { 
	protected int i; 
	public SetType(int i) { 
		this.i = i; 
	} 
	public int getI() { 
		return i; 
	}
	public boolean equals(Object o) { 
		return o instanceof SetType && ((SetType)o).getI() == i; 
	}
	public String toString() { 
		return String.valueOf(i); 
	}; 
} 
class HashType extends SetType {
	public HashType(int i) {
		super(i);
	} 
	public int hashCode() { 
		return i; 
	}
}
class TreeType extends SetType implements Comparable<TreeType> {
	public TreeType(int i) {
		super(i);
	}
	@Override
	public int compareTo(TreeType o) {
		return i < o.i? -1 :
						(i == o.i? 0: 1); 
	} 
}

public class TypesForSets {

	static <T> void fillSet(Set<T> set, Class<T> clazz) { 
		try {
			Constructor<T> constructor = clazz.getConstructor(int.class); 
			for(int i=1; i<=10; i++) { 
				set.add(constructor.newInstance(i)); 
			}
		} catch (Exception e) {
			new RuntimeException(e); 
		} 
	} 
	static <T> void test(Set<T> set, Class<T> clazz) { 
		fillSet(set, clazz); 
		fillSet(set, clazz); 
		fillSet(set, clazz); 
		System.out.println(set.getClass().getName() + "---" + clazz.getName()); 
		System.out.println(set); 
	} 
	public static void main(String[] args) { 
		test(new HashSet<HashType>(), HashType.class); 
		test(new LinkedHashSet<HashType>(), HashType.class); 
		test(new TreeSet<TreeType>(), TreeType.class); 
		
		//Things that don't work:
		test(new HashSet<SetType>(), SetType.class);
		test(new HashSet<TreeType>(), TreeType.class);
		test(new LinkedHashSet<SetType>(), SetType.class);
		test(new LinkedHashSet<TreeType>(), TreeType.class);
		
		try{ 
			test(new TreeSet<SetType>(), SetType.class);
		} catch(Exception e) { 
			e.printStackTrace(); 
		}
		try{ 
			test(new TreeSet<HashType>(), HashType.class);
		} catch(Exception e) { 
			e.printStackTrace(); 
		}
		
	}
	
}
